package TOOLS;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;

import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

/**
 * 文件处理工具
 * 
 * @author Akite
 *
 */
public class fileTool {

	public void newPath(String path) {
		File folder = new File(path);
		if (!folder.exists() && !folder.isDirectory()) {
			folder.mkdirs();
			System.out.println("创建文件夹");
		} else {
			System.out.println("文件夹已存在");
		}
	}

	public void deleteTxt(String path) {
		File ifile = new File(path);
		if (ifile.isFile()) {
			ifile.delete();
		}
	}

	/**
	 * 读取指定路径文件内容
	 * 
	 * @param path = 文件路径，包含文件名
	 * @return 文件内容字符串
	 * @throws Exception
	 */
	public String readTxt(String path) throws Exception {
		File file = new File(path);
		StringBuilder result = new StringBuilder();
		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fileInputStream, "utf-8");
			BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				if (result.length() > 0) {
					result.append(System.lineSeparator() + s);
				} else {
					result.append(s);
				}
			}
			br.close();
		} catch (Exception e) {
			throw new Exception("-12");
		}
		return result.toString();
	}

	public String readTxt(String path, String characterSet) throws Exception {
		File file = new File(path);
		StringBuilder result = new StringBuilder();
		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			InputStreamReader isr = null;
			if (characterSet == null) {
				isr = new InputStreamReader(fileInputStream);
			} else {
				isr = new InputStreamReader(fileInputStream, characterSet);
			}
			BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				if (result.length() > 0) {
					result.append(System.lineSeparator() + s);
				} else {
					result.append(s);
				}
			}
			br.close();
		} catch (Exception e) {
			throw new Exception("-12");
		}
		return result.toString();
	}

	/**
	 * 写出文本
	 * 
	 * @param pathName = 文本路径+名称
	 * @param content  = 内容
	 * @throws Exception
	 */
	public void writeTxt(String pathName, String content) throws Exception {
		try {
			if (pathName == null) {
				throw new Exception("-14");
			}
			File writeName = new File(pathName); // 相对路径，如果没有则要建立一个新的output.txt文件
			FileOutputStream fileOutputStream = new FileOutputStream(writeName);
			OutputStreamWriter osr = new OutputStreamWriter(fileOutputStream, "utf-8");
			osr.write(content);
			osr.close();
		} catch (IOException e) {
			throw new Exception("-14");
		}
	}

	public void writeTxt_characterSet(String pathName, String content, String characterSet) throws Exception {
		try {
			if (pathName == null) {
				throw new Exception("-14");
			}
			File writeName = new File(pathName); // 相对路径，如果没有则要建立一个新的output.txt文件
			FileOutputStream fileOutputStream = new FileOutputStream(writeName);
			OutputStreamWriter osr = null;
			if (characterSet == null) {
				osr = new OutputStreamWriter(fileOutputStream);
			} else {
				osr = new OutputStreamWriter(fileOutputStream, characterSet);
			}
			osr.write(content);
			osr.close();
		} catch (IOException e) {
			throw new Exception("-14");
		}
	}

	/**
	 * 写出文本
	 * 
	 * @param name    = 文本名称
	 * @param content = 内容
	 * @param path    = 路径
	 * @throws Exception
	 */
	public void writeTxt(String name, String content, String path) throws Exception {
		try {
			if (path == null) {
				path = ".";
			}
			if (path.substring(path.length() - 1, path.length()).equals("\\")) {
				path = path.substring(0, path.length() - 1);
			}
			File writeName = new File(path + "\\" + name); // 相对路径，如果没有则要建立一个新的output.txt文件
			FileOutputStream fileOutputStream = new FileOutputStream(writeName);
			OutputStreamWriter osr = new OutputStreamWriter(fileOutputStream, "utf-8");
			osr.write(content);
			osr.close();
		} catch (IOException e) {
			throw new Exception("-14");
		}
	}

	public void copyFile(String iFname,String oldPath, String newPath) {
		try {
			oldPath=oldPath+"\\"+iFname;
			newPath=newPath+"\\"+iFname;
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
//					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();

		}

	}

	/**
	 * 写出文本
	 * 
	 * @param name         = 文本名称 <BR>
	 * @param content      = 内容 <BR>
	 * @param path         = 路径 <BR>
	 * @param characterSet = 字符集 <BR>
	 * @throws Exception
	 */
	public void writeTxt(String name, String content, String path, String characterSet) throws Exception {
		try {
			if (path == null) {
				path = ".";
			}
			if (path.substring(path.length() - 1, path.length()).equals("\\")) {
				path = path.substring(0, path.length() - 1);
			}
			File writeName = new File(path + "\\" + name); // 相对路径，如果没有则要建立一个新的output.txt文件
			FileOutputStream fileOutputStream = new FileOutputStream(writeName);
			OutputStreamWriter osr = null;
			if (characterSet != null) {
				osr = new OutputStreamWriter(fileOutputStream, characterSet);
			} else {
				osr = new OutputStreamWriter(fileOutputStream);
			}
			osr.write(content);
			osr.close();
		} catch (IOException e) {
			throw new Exception("-14");
		}
	}

	/**
	 * 获取文本加密情况
	 * 
	 * @param str = 文本
	 * @return [0]=次数；[1]=参数
	 */
	public int[] getEncryptInfo(String str) {
		int[] info = new int[2];
		StringBuilder result = new StringBuilder();
		result.append(str);
		int[] mark = new int[3];
		mark[0] = result.indexOf("!AKS");
		if (mark[0] == -1) {
			info[0] = -1;
			info[1] = 0;
		} else {
			mark[1] = result.indexOf("|", mark[0]);
			mark[2] = result.indexOf("@", mark[1]);
			info[0] = Integer.parseInt(result.substring(mark[0] + 4, mark[1]));
			info[1] = Integer.parseInt(result.substring(mark[1] + 1, mark[2]));
		}
		return info;
	}

	/**
	 * 加密文本 '!AKS1|3@'
	 * 
	 * @param str= 待加密文本
	 * @return
	 */
	public String encrypt(String str, int key) {
		StringBuilder result = new StringBuilder();
		result.append(str);
		char[] encrypter = new char[result.length()];
		int count = getEncryptInfo(str)[0] + 1;
		if (count == 0) {
			count = 1;
		}
		for (int i = 0; i < result.length(); i++) {
			encrypter[i] = result.charAt(i);
//			int j=encrypter[i];
			encrypter[i] += key;
//			int k=encrypter[i];
//			System.out.println(""+k);
		}
		result = new StringBuilder().append(encrypter);
		String mark = "!AKS" + count + "|" + key + "@";
		return mark + result.toString();
	}

	/**
	 * 反加密（解密）一次
	 * 
	 * @param str = 待解密文本
	 * @return 解密结果文本
	 */
	public String unEncrypt(String str) {
		StringBuilder result = new StringBuilder();
		result.append(str);
		int[] info = new int[2];
		info = getEncryptInfo(str);
		if (info[0] == -1) {
			return str;
		} else {
			int h = result.indexOf("!AKS" + info[0] + "|");
			int s = result.indexOf("@", h);
			result = result.delete(0, s + 1);
			if (info[0] > 0) {
				char[] encrypter = new char[result.length()];
				for (int i = 0; i < result.length(); i++) {
					encrypter[i] = result.charAt(i);
//					int j=encrypter[i];
					encrypter[i] -= info[1];
//					int k=encrypter[i];
//					System.out.println(""+k);
				}
				result = new StringBuilder().append(encrypter);
			}
		}
		return result.toString();
	}

	/**
	 * 反加密（解密）至最终结果
	 * 
	 * @param str = 待解密文本
	 * @return 解密结果文本
	 */
	public String unEncrypts(String str) {
		int[] info = new int[2];
		info = getEncryptInfo(str);
		while (info[0] != -1) {
			str = unEncrypt(str);
			info = getEncryptInfo(str);
		}
		return str;
	}

	public String selectPath() {
		int result = 0;
		String path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			path = fileChooser.getSelectedFile().getPath();
			return path;
		}
		return null;
	}
	
	public String selectXLSM() throws Exception {
		int result = 0;
		String path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("xlsm", "XLSM");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			path = fileChooser.getSelectedFile().getPath();
			return path;
		}
		throw new Exception("-115");
	}
	
	public String selectTXT() throws Exception {
		int result = 0;
		String path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("txt", "TXT");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			path = fileChooser.getSelectedFile().getPath();
			return path;
		}
		throw new Exception("-115");
	}

	public String selectTXT(String defaultFileName) throws Exception {
		int result = 0;
		String path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("txt", "TXT");
		fileChooser.setFileFilter(filter);
		fileChooser.setSelectedFile(new File(defaultFileName));
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			path = fileChooser.getSelectedFile().getPath();
			return path;
		}
		throw new Exception("-115");
	}

	public String[] selectTXTs() throws Exception {
		int result = 0;
		String[] path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setMultiSelectionEnabled(true);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("txt", "TXT");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			File[] fs = fileChooser.getSelectedFiles();
			path = new String[fs.length];
			for (int i = 0; i < fs.length; i++) {
				path[i] = fs[i].getPath();
			}
			return path;
		}
		throw new Exception("-115");
	}

	public String selectCSVstr() throws Exception {
		int result = 0;
		String path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV", "csv");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			path = fileChooser.getSelectedFile().getPath();
			return path;
		}
		throw new Exception("-115");
	}

	public String selectSSA() throws Exception {
		int result = 0;
		String path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("ssa", "SSA");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			path = fileChooser.getSelectedFile().getPath();
			return path;
		}
		throw new Exception("-115");
	}

	public String[] selectSSAs() throws Exception {
		int result = 0;
		String[] path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setMultiSelectionEnabled(true);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("ssa", "SSA");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			File[] fs = fileChooser.getSelectedFiles();
			path = new String[fs.length];
			for (int i = 0; i < fs.length; i++) {
				path[i] = fs[i].getPath();
			}
			return path;
		}
		throw new Exception("-115");
	}

	public String selectJAR() throws Exception {
		int result = 0;
		String path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("jar", "JAR");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			path = fileChooser.getSelectedFile().getPath();
			return path;
		}
		throw new Exception("-115");
	}

	public String selectJAR(String iPath) throws Exception {
		int result = 0;
		String path = null;
		JFileChooser fileChooser = new JFileChooser();
		@SuppressWarnings("unused")
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
//		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setCurrentDirectory(new File(iPath));
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("jar", "JAR");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			path = fileChooser.getSelectedFile().getPath();
			return path;
		}
		throw new Exception("-115");
	}

	/**
	 * result[0]=fileName;<BR>
	 * result[1]=path;<BR>
	 * result[2]=path_fileName;<BR>
	 * 
	 * @return
	 * @throws Exception
	 */
	public String[] selectCSV() throws Exception {
		int result = 0;
		String[] path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setMultiSelectionEnabled(true);
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("csv", "CSV");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			path = new String[3];
			path[0] = fileChooser.getSelectedFile().getName();
			path[1] = fileChooser.getSelectedFile().getParent();
			path[2] = fileChooser.getSelectedFile().getPath();
			return path;
		}
		throw new Exception("-115");
	}

	public String[] selectCSVs() throws Exception {
		int result = 0;
		String[] path = null;
		JFileChooser fileChooser = new JFileChooser();
		FileSystemView fsv = FileSystemView.getFileSystemView(); // 注意了，这里重要的一句
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		fileChooser.setDialogTitle("请选择路径...");
		fileChooser.setApproveButtonText("确定");
		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		fileChooser.setMultiSelectionEnabled(true);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("csv", "CSV");
		fileChooser.setFileFilter(filter);
		result = fileChooser.showOpenDialog(null);
		if (JFileChooser.APPROVE_OPTION == result) {
			File[] fs = fileChooser.getSelectedFiles();
			path = new String[fs.length];
			for (int i = 0; i < fs.length; i++) {
				path[i] = fs[i].getPath();
			}
			return path;
		}
		throw new Exception("-115");
	}

	public String[] readXLSline2(String iPath_Name) throws Exception {
		String[] result = new String[10];
		File file = new File(iPath_Name);
		FileInputStream fIP = new FileInputStream(file);
		Workbook wb = WorkbookFactory.create(fIP);
		Sheet st = wb.getSheetAt(0);
		DataFormatter formatter = new DataFormatter();
		for (int i = 0; i < result.length; i++) {
			result[i] = formatter.formatCellValue(st.getRow(1).getCell(i));
		}
		return result;
	}
}
